package com.example.myapplication.Entity;



import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.myapplication.Entity.MessageEntity;
import com.example.myapplication.R;

import java.util.List;

public class SendBoxAdapter extends BaseAdapter {
    private List<MessageEntity> messageList;
    private Context context;
    // 构造函数
    public SendBoxAdapter(Context context, List<MessageEntity> messageList) {
        this.context = context;
        this.messageList = messageList;
    }

    @Override
    public int getCount() {
        return messageList.size();
    }

    @Override
    public Object getItem(int position) {
        return messageList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    // 创建或重用视图
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.messge_box, parent, false);
                holder = new ViewHolder();
                holder.RemessageLayout = convertView.findViewById(R.id.right_message);
                holder.LemessageLayout = convertView.findViewById(R.id.left_message);
                holder.SendmessageText = convertView.findViewById(R.id.send_text);
                holder.RemessageText = convertView.findViewById(R.id.recive_text);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        String message = messageList.get(position).getMesssage();
        boolean state=messageList.get(position).getState();
        holder.SendmessageText.setText(message);
        holder.RemessageText.setText(message);

        // 根据状态变量来更新布局的可见性

        if (!state) {
            holder.LemessageLayout.setVisibility(View.GONE);
            holder.RemessageLayout.setVisibility(View.VISIBLE);
        } else {
            holder.LemessageLayout.setVisibility(View.VISIBLE);
            holder.RemessageLayout.setVisibility(View.GONE);
        }
        return convertView;
    }


    // 内部类，用于优化视图的创建和访问
    static class ViewHolder {
        TextView SendmessageText;
        TextView RemessageText;
        LinearLayout LemessageLayout;
        LinearLayout RemessageLayout;
    }

    public void setMessages(List<MessageEntity> messages) {
        messageList = messages;
        notifyDataSetChanged(); // 刷新适配器

    }

}


